// 工具模块 - 包含辅助函数

// 防 XSS
export function escapeHtml(text) {
  const div = document.createElement('div');
  div.textContent = text;
  return div.innerHTML;
}

// 使弹窗可拖拽
export function dragElement(el) {
  let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  const header = el.querySelector('.modal-header');

  if (!header) return;

  header.onmousedown = dragMouseDown;

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    el.style.top = (el.offsetTop - pos2) + "px";
    el.style.left = (el.offsetLeft - pos1) + "px";
  }

  function closeDragElement() {
    document.onmouseup = null;
    document.onmousemove = null;
  }
}

// 使按钮可拖拽
export function dragButton(btn, onClick) {
  let startX = 0, startY = 0, initialLeft = 0, initialBottom = 0;
  let isDragging = false;
  const dragThreshold = 5; // 拖拽阈值，像素单位

  btn.onmousedown = dragMouseDown;

  function dragMouseDown(e) {
    e = e || window.event;
    
    // 获取初始鼠标位置
    startX = e.clientX;
    startY = e.clientY;
    
    // 获取按钮的初始位置
    const computedStyle = window.getComputedStyle(btn);
    initialLeft = parseInt(computedStyle.left);
    initialBottom = parseInt(computedStyle.bottom);
    
    // 添加鼠标移动和释放事件监听器
    document.onmousemove = elementDrag;
    document.onmouseup = closeDragElement;
  }

  function elementDrag(e) {
    e = e || window.event;
    
    // 计算鼠标移动的距离
    const deltaX = Math.abs(e.clientX - startX);
    const deltaY = Math.abs(e.clientY - startY);
    
    // 如果移动距离超过阈值，则认为是拖拽操作
    if (!isDragging && (deltaX > dragThreshold || deltaY > dragThreshold)) {
      isDragging = true;
      // 阻止默认行为，防止拖拽时选中文本等
      e.preventDefault();
    }
    
    // 如果正在拖拽，则更新按钮位置
    if (isDragging) {
      // 计算鼠标移动的偏移量
      const offsetX = e.clientX - startX;
      const offsetY = e.clientY - startY;
      
      // 计算按钮的新位置
      const newLeft = initialLeft + offsetX;
      const newBottom = initialBottom - offsetY; // 注意这里是减号，因为bottom是从底部计算的
      
      // 应用新位置，保持使用bottom和left
      btn.style.left = newLeft + "px";
      btn.style.bottom = newBottom + "px";
    }
  }

  function closeDragElement(e) {
    // 清除事件监听器
    document.onmouseup = null;
    document.onmousemove = null;
    
    // 如果没有拖拽，则触发点击事件
    if (!isDragging && onClick) {
      onClick(e);
    }
    
    // 重置拖拽状态
    isDragging = false;
  }
}